import jwt
import logging
from datetime import datetime, timedelta
from typing import Optional, Dict, Any
from jwt.exceptions import PyJWTError

logger = logging.getLogger(__name__)

# JWT配置
SECRET_KEY = "your-secret-key-here"
ALGORITHM = "HS256"
ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7  # 7天
REFRESH_TOKEN_EXPIRE_DAYS = 30  # 30天

def create_access_token(subject: str) -> str:
    """创建访问令牌"""
    try:
        expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
        
        payload = {
            "sub": str(subject),
            "exp": expire,
            "iat": datetime.utcnow(),
            "type": "access"
        }
        
        logger.info(f"创建访问令牌: subject={subject}")
        return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
        
    except Exception as e:
        logger.error(f"创建访问令牌失败: {str(e)}")
        raise

def create_refresh_token(subject: str) -> str:
    """创建刷新令牌"""
    try:
        expire = datetime.utcnow() + timedelta(days=REFRESH_TOKEN_EXPIRE_DAYS)
        
        payload = {
            "sub": str(subject),
            "exp": expire,
            "iat": datetime.utcnow(),
            "type": "refresh"
        }
        
        logger.info(f"创建刷新令牌: subject={subject}")
        return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
        
    except Exception as e:
        logger.error(f"创建刷新令牌失败: {str(e)}")
        raise

def verify_token(token: str) -> Optional[Dict[str, Any]]:
    """验证令牌"""
    try:
        return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
    except PyJWTError as e:
        logger.error(f"令牌验证失败: {str(e)}")
        return None

def get_user_id_from_token(token: str) -> Optional[str]:
    """从令牌中获取用户ID"""
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        return payload.get("sub")
    except PyJWTError as e:
        logger.error(f"从令牌获取用户ID失败: {str(e)}")
        return None

# 为了向后兼容
JWTError = PyJWTError 